package com.moujitx.aliyuniot.emulator.app;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    //连接参数
    String pub_topic = "/sys/icmzmjztnzv/device02/thing/event/property/post";
    String sub_topic = "/sys/icmzmjztnzv/device02/thing/service/property/set";
    String clientId = "icmzmjztnzv.device02|securemode=2,signmethod=hmacsha256,timestamp=1696926830331|";
    String mqttHostUrl = "tcp://iot-06z00f41p02vz6s.mqtt.iothub.aliyuncs.com:1883";
    String username = "device02&icmzmjztnzv";
    String password = "8637265d2f4421f4340547874ab499affed5308d20322c01bcf96b82589bd8b7";

    String device_log = "";

    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;
    private ScheduledExecutorService scheduler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_dataPost = findViewById(R.id.btn_dataPost);
        Switch switch_led = findViewById(R.id.switch_led);
        Switch switch_mode = findViewById(R.id.switch_mode);
        EditText et_humidity = findViewById(R.id.et_humidity);
        TextView tv_log = findViewById(R.id.tv_log);
        TextView tv_mqtt = findViewById(R.id.tv_mqtt);


        btn_dataPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                postData(switch_led,switch_mode,et_humidity);
            }
        });

        switch_led.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //led开关
            }
        });

        switch_mode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //模式切换
            }
        });

        handler = new Handler(Looper.myLooper()) {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        break;
                    case 2:  // 反馈回传
                        break;
                    case 3:  //MQTT 收到消息回传   UTF8Buffer msg=new UTF8Buffer(object.toString());
                        String message = msg.obj.toString();
                        try {
                            JSONObject jsonObjectALL = null;
                            jsonObjectALL = new JSONObject(message);
                            setLog(jsonObjectALL.toString(), tv_log);

                            if (jsonObjectALL.getJSONObject("items").has("Mode")) {
                                int mode = jsonObjectALL.getJSONObject("items").getJSONObject("Mode").getInt("value");
                                if (mode == 0) {
                                    switch_mode.setChecked(false);
                                } else {
                                    switch_mode.setChecked(true);
                                }
                            }

                            if (jsonObjectALL.getJSONObject("items").has("LEDSwitch")) {
                                int LEDSwitch = jsonObjectALL.getJSONObject("items").getJSONObject("LEDSwitch").getInt("value");
                                if (LEDSwitch == 0) {
                                    switch_led.setChecked(false);
                                } else {
                                    switch_led.setChecked(true);
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            break;
                        }
                        break;
                    case 30:  //连接失败
                        // Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        tv_mqtt.setText("未连接");
                        break;
                    case 31:   //连接成功
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        tv_mqtt.setText("已连接");
                        try {
                            client.subscribe(sub_topic, 1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };

        mqtt_init();
        start_reconnect();


        //定时更改湿度，模拟实时监测
        Timer timer = new Timer();

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Random random = new Random();
                int humidity_random = random.nextInt(100);
                et_humidity.setText(String.valueOf(humidity_random));
                postData(switch_led, switch_mode, et_humidity);
            }
        };
        timer.schedule(task,0, 1000);  // 第一个参数是要执行的任务，第二个参数是延迟多少毫秒后开始执行，第三个参数是每隔多少毫秒重复执行一次

    }

    private void postData(Switch switch_led, Switch switch_mode, EditText et_humidity){
        //上报数据
        String ledSwitch = switch_led.isChecked() ? "1" : "0";  //开关状态 1开   0关
        String mode = switch_mode.isChecked() ? "1" : "0";      //工作模式 1手动 0自动
        String humidity = String.valueOf(et_humidity.getText());  //温度数据
        String payload = "{\"params\":{\"LEDSwitch\":"+ledSwitch+",\"Mode\":"+mode+",\"Humidity\":"+humidity+"},\"version\":\"1.0.0\"}";

        publish_message(payload);
    }

    private void mqtt_init() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            System.out.println(">>>" + mqttHostUrl);
            System.out.println(">>>" + clientId);

            //connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);

            client = new MqttClient(mqttHostUrl, clientId, new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(username);
            //设置连接的密码
            options.setPassword(password.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(60);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    //封装message包
                    msg.what = 3;   //收到消息标志位
                    msg.obj =message.toString();
                    //发送messge到handler
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!(client.isConnected()))  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        // 没有用到obj字段
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    // 没有用到obj字段
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void start_reconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    public void disconnect() {
        try {
            client.disconnect();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void publish_message(String message) {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage mqtt_message = new MqttMessage();
        mqtt_message.setPayload(message.getBytes());
        try {
            client.publish(pub_topic, mqtt_message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private void setLog(String msg, TextView tv_log){
        device_log = msg + "\n\n" + device_log;
        tv_log.setText(device_log);
        tv_log.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

}